import hashlib
import json
import random
import time
import uuid

import execjs
import execjs._runner_sources as _runner_sources
import requests

from core import Cipher, getSign, jdGsService, body_dec, body_enc
from util import (
    dict_json
)

md5 = hashlib.md5()
sess = requests.session()
local_node_runtime = execjs.ExternalRuntime(
    name="Node.js (V8) local",
    command='',
    encoding='UTF-8',
    runner_source=_runner_sources.Node
)
local_node_runtime._binary_cache = ['./node.exe']
local_node_runtime._available = True
execjs.register('local_node', local_node_runtime)
encryptInfo = {
    'a8b69': {'tk': 'tk02wb5ff1c9518naQJXS0q3aBOBLnuh5UoSKtkMLwMLro/Xzno1JCJCml2SoltsTevoK3pjQaGXHA7naAbAPzwEhQ/N',
              'rd': 'V3oD1ui0Tgns', 'enc': 'HmacMD5', 'fp': '9046022772675391'}
}
algo_info = {
    'a8b69': {'tk': 'tk03wa3fb1c9418nbkA8M0PkCPdWxnoT0BOObqfbfssMGCLn94SeSWKMOmtKvMcR555O79WzkqGQ1c3OqeyzPcwJumlh',
              'fp': 'g99i5mn6z99yyt97', 'rd': 'g0KfGLcT0SgX', 'enc': 'SHA512'}}
from urllib.parse import urlencode, urljoin

wskey = 'AAJn-LN1AEDr9z_MN4-gL4sxtOhb4FLrELrpbOJchQ0sVM-x3z9JqeWJhaXtPt49cEJ_ZfQ6LHOd0hGdcyit1SyaqYG_t9kX'
deviceId = 'af7bace04f0ccea6'
eid = 'eidAe04a812220s8k95RQ8IITpeRtmsfde9frZPeUtXLFH0Ty7i10siZiNj2p4HHn5HoXDFPpp115ISi+HUeogHvfjYNgUIlcKXnzDRJbhU4JN5+ucAw'
clientVersion = '15.0.25'
ep = {
    'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
    'ts': round(time.time() * 1000),
    'ridx': -1,
    'cipher': {
        'd_brand': 'YwnrY2jzaQPyam==',
        'openudid': body_enc(data=deviceId),
        'screen': 'CJuyCMenCNqm',
        'area': 'CJvpCJYmCV8zDtCzXzYzCtG0',
        'uuid': body_enc(data=deviceId),
        'osVersion': 'Dy4nBtS=',
        'wifiBssid': 'dW5hbw93bq==',
        'd_model': 'U0jXBUOm',
        'aid': body_enc(data=deviceId),
    },
    'ciphertype': 5,
    'version': '1.2.0',
    'appname': 'com.jingdong.app.mall'
}
ep = dict_json(ep)
cookies = 'wskey=AAJoAfWAAEBsTfu0MaaMj5iB5NHkPg7tNBIZViJq8jwIo1Ynz_Y4l-c9mwOSmAI47tlAUevUbx8RjyHBtsj1l7CIsO7UwTtf;whwswswws=JD012145b9dJdMDPXjCf174511965858206qO399cMR3NkdASfx4a17yAQ2P7l14Ee0jrKff4PJa9WSiYeFee3FkP0qiJ_5KgO7T0f831211hX1TZmdAsXQFw1luo70c~BApXSok40UvNC9q4Q8kfutLLJaXe7acp28Q1NyYlr9xJ1ItZfQtKPwUq_1S7-Z9BxJeT6HyqBNur1R4w;unionwsws={"devicefinger":"eidAe04a812220s8k95RQ8IITpeRtmsfde9frZPeUtXLFH0Ty7i10siZiNj2p4HHn5HoXDFPpp115ISi+HUeogHvfjYNgUIlcKXnzDRJbhU4JN5+ucAw","jmafinger":"JD012145b9dJdMDPXjCf174511965858206qO399cMR3NkdASfx4a17yAQ2P7l14Ee0jrKff4PJa9WSiYeFee3FkP0qiJ_5KgO7T0f831211hX1TZmdAsXQFw1luo70c~BApXSok40UvNC9q4Q8kfutLLJaXe7acp28Q1NyYlr9xJ1ItZfQtKPwUq_1S7-Z9BxJeT6HyqBNur1R4w"};x-rp-evtoken=mGW9U4qbzsaBdCMe70m9pIc7ouw84X2x2frSlxpeH9NGn7zPuHr0FhaembzZbPLuTIHb159gdQk3ObQm2o2dHA==;sdtoken=AAbEsBpEIOVjqTAKCQtvQu17jJPi9cR6qoIARiVr6Ls4lYfKgbs9mg5p6gnajdgbM05j-ZTjqUD-IXV-4AZ6N2cl9ASDkvDxJv4L8Fp0Rt-dQVq_BE82sKBTib6M4179F71GojtOx1u1eGeGfUMGeuzMdQQea9VPvaQ;pin_hash=-1117554224;'
jec = '%7B%22hdid%22%3A%22JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw%3D%22%2C%22ts%22%3A1745119644450%2C%22ridx%22%3A-1%2C%22cipher%22%3A%7B%22pin%22%3A%22awHpDNuzCNG5ZWG0DwS2CG%3D%3D%22%7D%2C%22ciphertype%22%3A5%2C%22version%22%3A%221.2.0%22%2C%22appname%22%3A%22com.jingdong.app.mall%22%7D'
api_token = 'jdd01VEDTZ2MHO2RN7UOL7IRRHH3V753LIOYEY7PWIEHYY725SB4W7CEIAYJVIAKCEHI2IT5T7SMHIHNOFR45O2VWK4QCDAA6PJVQZF3XIIQ01234567'
skuid = '10105209822387'
subCartSkuList = list()
uts = '0f31TVRjBSuRxEAwTUUYodjQwgOD2S9jBpPw+9zcKSN62DSOzhHE37K3aaxhCjgvUqhr1S/dzdDLGAcbLL0bKNmNlbHSX3htQF4Myqj+PVQLKDB+qjCJIBojRI7FLMA25GXWZ7Teoifgo79Rjx5WU2hnAk2ynctUKz0AiQxHpr1dhDQq0d+qZvqmn+9WPbPox6FAM1lzYqaVt7Tdh+YcLw=='


def get_uts():
    functionId = 'newUserInfo'
    body_data = '{"flag":"nickname","fromSource":1,"sourceLevel":1}'
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=clientVersion, uuid=deviceId)
    result = sign.split('&')
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'user-agent': 'sprite/1.0.0;jdmall;android;version/13.2.9',
        'x-rp-client': 'android_4.0.0',
        'X-referer-package': 'com.jingdong.app.mall',
        'charset': 'UTF-8',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-httpdns-route': '111.202.127.106',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'accept-encoding': 'br,gzip,deflate',
        'x-pp-aew': '68',
        'cache-control': 'no-cache',
        'j-e-c': jec,
        "Cookie": cookies
    }
    params = {
        'functionId': functionId,
        'clientVersion': clientVersion,
        'build': '100533',
        'client': 'android',
        'partner': 'jingdong',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-2-0',
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': api_token,
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.16.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        'body': body_data
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = sess.post(url=url, headers=headers, params=params, data=data, verify=False, impersonate="chrome99_android")
    print(resp.text)


def appPoint():
    functionId = 'appoint'
    body_data = '{"autoAddCart":"0","bsid":"","check":"0","ctext":"","isShowCode":"0","mad":"0","skuId":"100198527976","type":"4"}'
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=clientVersion, uuid=deviceId)
    result = sign.split('&')
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'user-agent': 'sprite/1.0.0;jdmall;android;version/13.2.9',
        'x-rp-client': 'android_4.0.0',
        'X-referer-package': 'com.jingdong.app.mall',
        'charset': 'UTF-8',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-httpdns-route': '111.202.127.106',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'accept-encoding': 'br,gzip,deflate',
        'x-pp-aew': '68',
        'cache-control': 'no-cache',
        'j-e-c': jec,
        "Cookie": cookies
    }
    params = {
        'functionId': functionId,
        'clientVersion': clientVersion,
        'build': '100533',
        'client': 'android',
        'partner': 'jingdong',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-2-0',
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': api_token,
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.16.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        'body': body_data
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = sess.post(url=url, headers=headers, params=params, data=data, verify=False, impersonate="chrome99_android")
    print(resp.text)


def get_address():
    functionId = 'getAddressByPin'
    body_data = '{"isLastOrder":true,"latitude":"","longitude":"","settlementVersionCode":2540}'
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=clientVersion, uuid=deviceId)
    result = sign.split('&')
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'user-agent': 'sprite/1.0.0;jdmall;android;version/13.2.9',
        'x-rp-client': 'android_4.0.0',
        'X-referer-package': 'com.jingdong.app.mall',
        'charset': 'UTF-8',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-httpdns-route': '111.202.127.106',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'accept-encoding': 'br,gzip,deflate',
        'x-pp-aew': '68',
        'cache-control': 'no-cache',
        'j-e-c': jec,
        "Cookie": cookies
    }
    params = {
        'functionId': functionId,
        'clientVersion': clientVersion,
        'build': '100533',
        'client': 'android',
        'partner': 'jingdong',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-2-0',
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': api_token,
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.16.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        'body': body_data
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = sess.post(url=url, headers=headers, params=params, data=data, verify=False, impersonate="chrome99_android")
    print(resp.text)


def cart():
    functionId = 'cart'
    body_data = '{"addressId":"5980268519","appleCare":0,"businessId":"","cartBundleVersion":"15020","cartRequestType":17,"cartuuid":"2a836928-e37a-4092-8802-f5cb0c4a8cfd","configVersion":254,"coord_type":"","curConfigLan":"zh","cvhv":"-141339542449745","degradation":0,"euCountry":false,"filterTag":"6666","hasSearchParam":false,"hitNewUIStatus":0,"homeWishListUserFlag":"3","isDegradeToZh":"0","latitude":"25.01156","longitude":"112.581155","moduleVersions":{"android_cart":"15020"},"mqTriggerStatus":"0","page":1,"pagingAb":"A","requestFrom":1,"siteId":0,"supportPaging":"1","syntype":"1","tabMenuValue":"","updateTag":true,"userType":"1"}'
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=clientVersion, uuid=deviceId)
    result = sign.split('&')
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'Cookie': 'wskey=AAJoAfWAAEBsTfu0MaaMj5iB5NHkPg7tNBIZViJq8jwIo1Ynz_Y4l-c9mwOSmAI47tlAUevUbx8RjyHBtsj1l7CIsO7UwTtf;whwswswws=JD012145b9dJdMDPXjCf174511965858206qO399cMR3NkdASfx4a17yAQ2P7l14Ee0jrKff4PJa9WSiYeFee3FkP0qiJ_5KgO7T0f831211hX1TZmdAsXQFw1luo70c~BApXSok40UvNC9q4Q8kfutLLJaXe7acp28Q1NyYlr9xJ1ItZfQtKPwUq_1S7-Z9BxJeT6HyqBNur1R4w;unionwsws={"devicefinger":"eidAe04a812220s8k95RQ8IITpeRtmsfde9frZPeUtXLFH0Ty7i10siZiNj2p4HHn5HoXDFPpp115ISi+HUeogHvfjYNgUIlcKXnzDRJbhU4JN5+ucAw","jmafinger":"JD012145b9dJdMDPXjCf174511965858206qO399cMR3NkdASfx4a17yAQ2P7l14Ee0jrKff4PJa9WSiYeFee3FkP0qiJ_5KgO7T0f831211hX1TZmdAsXQFw1luo70c~BApXSok40UvNC9q4Q8kfutLLJaXe7acp28Q1NyYlr9xJ1ItZfQtKPwUq_1S7-Z9BxJeT6HyqBNur1R4w"};pin_hash=-1117554224;',
        'x-referer-package': 'com.jingdong.app.mall',
        'x-pp-aew': '64',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'x-httpdns-route': '240.0.0.12',
        'charset': 'UTF-8',
        'j-e-c': '%7B%22hdid%22%3A%22JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw%3D%22%2C%22ts%22%3A1745119644450%2C%22ridx%22%3A-1%2C%22cipher%22%3A%7B%22pin%22%3A%22awHpDNuzCNG5ZWG0DwS2CG%3D%3D%22%7D%2C%22ciphertype%22%3A5%2C%22version%22%3A%221.2.0%22%2C%22appname%22%3A%22com.jingdong.app.mall%22%7D',
        'x-rp-client': 'android_4.0.0',
        'user-agent': 'okhttp/3.12.16;jdmall;android;version/15.0.25;build/100533;',
        'cache-control': 'no-cache',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    params = {
        'functionId': functionId,
        'clientVersion': clientVersion,
        'build': '100533',
        'client': 'android',
        'partner': 'vivo',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-1-0',
        'uts': uts,
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': api_token,
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'bef': "1",
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        "body": '{"hdid":"JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=","ts":1744781687702,"ridx":-1,"cipher":{"body":"%s"},"ciphertype":5,"version":"1.2.0","appname":"com.jingdong.app.mall"}' % body_enc(
            data=body_data)
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = requests.post(url=url, headers=headers, params=params, data=data, verify=False,
                         impersonate="chrome99_android")
    print(resp.text)
    resp_json = json.loads(resp.text)
    if resp_json.get('cartInfo'):
        for i in resp_json['cartInfo']['vendors'] + resp_json['cartInfo']['unusableSkus'] if resp_json[
            'cartInfo'].get('unusableSkus') else resp_json['cartInfo']['vendors']:
            if i.get('sorted'):
                for j in i['sorted']:
                    if j['item'].get('items'):
                        for k in j['item']['items']:
                            subCartSkuList.append({
                                'Id': k['item']['Id'],
                                'num': k['item']['Num'],
                                'skuUuid': k['item']['skuUuid']
                            })
                    else:
                        subCartSkuList.append({
                            'Id': j['item']['Id'],
                            'num': 1,
                            'skuUuid': j['item']['skuUuid']
                        })
            else:

                subCartSkuList.append({
                    'Id': i['Id'],
                    'num': i['Num'],
                    'skuUuid': i['skuUuid']
                })


def batchDelete():
    print('清除购物车')
    functionId = 'cartRemove'
    body_data = {'addressId': '0', 'appleCare': 0, 'businessId': '', 'cartBundleVersion': '11100',
                 'cartuuid': str(uuid.uuid4()), 'configVersion': 249, 'coord_type': '',
                 'cvhv': '', 'degradation': 0, 'hitNewUIStatus': 1, 'homeWishListUserFlag': '2',
                 'latitude': '', 'longitude': '', 'mqTriggerStatus': '0',
                 'operations': [{'TheSkus': subCartSkuList,
                                 'carttype': '4'}],
                 'syntype': '1', 'updateTag': False, 'userType': '1'}
    body_data = dict_json(body_data)
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=clientVersion, uuid=deviceId)
    result = sign.split('&')
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'Cookie': 'wskey=AAJoAfWAAEBsTfu0MaaMj5iB5NHkPg7tNBIZViJq8jwIo1Ynz_Y4l-c9mwOSmAI47tlAUevUbx8RjyHBtsj1l7CIsO7UwTtf;whwswswws=JD012145b9dJdMDPXjCf174511965858206qO399cMR3NkdASfx4a17yAQ2P7l14Ee0jrKff4PJa9WSiYeFee3FkP0qiJ_5KgO7T0f831211hX1TZmdAsXQFw1luo70c~BApXSok40UvNC9q4Q8kfutLLJaXe7acp28Q1NyYlr9xJ1ItZfQtKPwUq_1S7-Z9BxJeT6HyqBNur1R4w;unionwsws={"devicefinger":"eidAe04a812220s8k95RQ8IITpeRtmsfde9frZPeUtXLFH0Ty7i10siZiNj2p4HHn5HoXDFPpp115ISi+HUeogHvfjYNgUIlcKXnzDRJbhU4JN5+ucAw","jmafinger":"JD012145b9dJdMDPXjCf174511965858206qO399cMR3NkdASfx4a17yAQ2P7l14Ee0jrKff4PJa9WSiYeFee3FkP0qiJ_5KgO7T0f831211hX1TZmdAsXQFw1luo70c~BApXSok40UvNC9q4Q8kfutLLJaXe7acp28Q1NyYlr9xJ1ItZfQtKPwUq_1S7-Z9BxJeT6HyqBNur1R4w"};pin_hash=-1117554224;',
        'x-referer-package': 'com.jingdong.app.mall',
        'x-pp-aew': '64',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'x-httpdns-route': '240.0.0.12',
        'charset': 'UTF-8',
        'j-e-c': '%7B%22hdid%22%3A%22JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw%3D%22%2C%22ts%22%3A1745119644450%2C%22ridx%22%3A-1%2C%22cipher%22%3A%7B%22pin%22%3A%22awHpDNuzCNG5ZWG0DwS2CG%3D%3D%22%7D%2C%22ciphertype%22%3A5%2C%22version%22%3A%221.2.0%22%2C%22appname%22%3A%22com.jingdong.app.mall%22%7D',
        'x-rp-client': 'android_4.0.0',
        'user-agent': 'okhttp/3.12.16;jdmall;android;version/15.0.25;build/100533;',
        'cache-control': 'no-cache',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    params = {
        'functionId': functionId,
        'clientVersion': clientVersion,
        'build': '100533',
        'client': 'android',
        'partner': 'vivo',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-1-0',
        'uts': uts,
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': api_token,
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'bef': "1",
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        "body": '{"hdid":"JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=","ts":1744781687702,"ridx":-1,"cipher":{"body":"%s"},"ciphertype":5,"version":"1.2.0","appname":"com.jingdong.app.mall"}' % body_enc(
            data=body_data)
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = requests.post(url=url, headers=headers, params=params, data=data, verify=False,
                         impersonate="chrome99_android")
    print(resp.text)


def cartAdd():
    uid = deviceId
    functionId = 'cartAdd'
    body_data = '{"addressId":"1480474950","appleCare":0,"businessId":"","businessName":"browserhistory","cartBundleVersion":"15020","cartuuid":"103a4c26-9540-41e0-a31c-fbe8a2481131","configVersion":254,"coord_type":"","cvhv":"-141339542449745","degradation":0,"hitNewUIStatus":0,"homeWishListUserFlag":"3","isDegradeToZh":"0","latitude":"23.123103","longitude":"113.393509","moduleVersions":{"android_cart":"15020"},"mqTriggerStatus":"1","noResponse":true,"operations":[{"TheSkus":[{"Id":"100180585436","num":"1"}],"carttype":"2"}],"siteId":0,"syntype":"1","userType":"2"}'
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion='15.0.25',
                   uuid=uid)
    result = sign.split('&')
    ep = {
        'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
        'ts': round(time.time() * 1000),
        'ridx': -1,
        'cipher': {
            'area': 'CJvpCJYmCV8zDtCzXzYzCtG0',
            'd_model': 'U0jXBUOm',
            'wifiBssid': 'dW5hbw93bq==',
            'osVersion': 'Dy4nBtS=',
            'd_brand': 'YwnrY2jzaQPyam==',
            'screen': 'CJuyCMenCNqm',
            'uuid': Cipher.encrypt(bytearray(uid, 'utf-8')),
            'aid': Cipher.encrypt(bytearray(uid, 'utf-8')),
            'openudid': Cipher.encrypt(bytearray(uid, 'utf-8'))
        },
        'ciphertype': 5,
        'version': '1.2.0',
        'appname': 'com.jingdong.app.mall'
    }
    ep = dict_json(ep)
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.0; VTR-TL00 Build/HUAWEIVTR-TL00)',
        'X-Rp-Client': 'android_4.0.0',
        'X-Referer-Package': 'com.jingdong.app.mall',
        'charset': 'UTF-8',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'accept-encoding': 'br,gzip,deflate',
        'x-pp-aew': '68',
        'cache-control': 'no-cache',
        # 'j-e-c': '%7B%22hdid%22%3A%22JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw%3D%22%2C%22ts%22%3A1744779817284%2C%22ridx%22%3A-1%2C%22cipher%22%3A%7B%22pin%22%3A%22oxPiTUU1TJunTUO4TUU1TUTLTJq2TUU2TJvOTUO1%22%7D%2C%22ciphertype%22%3A5%2C%22version%22%3A%221.2.0%22%2C%22appname%22%3A%22com.jingdong.app.mall%22%7D',
        "Cookie": 'pin=zql%E5%91%A8%E5%BA%86%E6%9D%A5;wskey=AAJn_gynAEAN08OdDEeoWgbz-Ujpdrguy2Mokeo4nPMDH-rFlVRpGHeWwmdWS2X2WAIsAQfGY6-AzeP8uQv8_3c2-DQpNZzT;whwswswws=JD012145b9qDDXwUnpaP174479120098506jFfdr8lyxyCemeyaFpFGj9G1FrkbS6xDEarcIcBIjhmFToXmljS8Bye1xuVoHNdXiqfA0Xo3Ywzzbcoc2KqCDA07kniq9~BApXSbH2gPvNC9q4Q8kfutLLJaXe7P4yRehjRxopo9xJ1PsZKcQMnWp8xaq0H9kR17LI4;unionwsws={"devicefinger":"eidAa9b58121bas7HsrvWCEWS+CS8JIFBmD9PR7K8O5evzcqAwm2TWwFbe8znFDGa3fERUFCY2NtLvU24R16a2bfnbzaeg9JNymLlo1yI1kkdVEXnYVU","jmafinger":"JD012145b9qDDXwUnpaP174479120098506jFfdr8lyxyCemeyaFpFGj9G1FrkbS6xDEarcIcBIjhmFToXmljS8Bye1xuVoHNdXiqfA0Xo3Ywzzbcoc2KqCDA07kniq9~BApXSbH2gPvNC9q4Q8kfutLLJaXe7P4yRehjRxopo9xJ1PsZKcQMnWp8xaq0H9kR17LI4"};'
    }
    params = {
        'functionId': functionId,
        'clientVersion': '15.0.25',
        'build': '100533',
        'client': 'android',
        'partner': 'vivo',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-1-0',
        'uts': '0f31TVRjBSsqndu4/jgUPz6uymy50MQJ3ueHZX4h9XKSljTYF8eCJ/xbWZvV6y5O6vprxbl1rlVCHvTciCDLHtQ1bGYVFYsf9WMSTbkcHXcqkVPYcknCk1UfMum5av5eoBjf/Hna/zF8A/z08GpHam26e1zu3KxHUmwobOJZyGAz+7XTX5VcrYcmf2Rc9znOB2rY41jbI8AmamF0VNZjsQ==',
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': 'jdd01CW6MMBXHWTISTANFQMYZH7I4H23AKHODVCTA7HJ7XQAKKU3MYUWD7AB7BHKBFPK4EGZWWMVLC3ASW2K6OZBORGZUUXAURVGB4ZZSLGI01234567',
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.5.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'bef': "1",
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        "body": '{"hdid":"JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=","ts":1744781687702,"ridx":-1,"cipher":{"body":"%s"},"ciphertype":5,"version":"1.2.0","appname":"com.jingdong.app.mall"}' % body_enc(
            data=body_data)
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = requests.post(url=url, headers=headers, params=params, data=data, verify=False,
                         impersonate="chrome99_android")
    print(resp.text)


def currentOrder():
    functionId = 'currentOrder'
    body_data = '{"AppKeplerParams":{"otherData":{"mopenbp5":""}},"CartStr":{"TheSkus":[{"Id":"' + skuid + '","num":"1"}]},"OrderStr":{},"addressGlobal":true,"allCheckedBuyLicenseIds":"","appEID":"' + eid + '","cartAdd":{"atmosphereList":[],"extFlag":{},"layerFlag":true,"layerType":"3","wareId":"' + skuid + '","wareNum":"1"},"cashierDeviceInfo":{"fk_aid":"' + deviceId + '","fk_appId":"com.jingdong.app.mall","fk_latitude":"mzvSKsJtcnCH3q9EhickfA==","fk_longtitude":"4YHWSVgTHrycpgj5lNYXoQ==","fk_terminalType":"02","fk_traceIp":"172.16.1.56","hasAndroidPay":"0","hasCyberMoneyPay":"0","hasHuaweiPay":"0","hasOCPay":"0","hasQQPay":"0","hasUPPay":"0","jdPaySdkVersion":"4.01.49.00","sdkToken":"","supportNFC":"1"},"cashierNewPrePay":false,"decryptType":"CBC","giftType":0,"hasSelectedOTC":"0","isDegradeToZh":"0","isLastOrder":true,"isRefreshOrder":false,"isSupportAllInvoice":true,"isUI14Enable":true,"operationType":0,"otcMergeSwitch":"1","param4ALayerMap":{"supportColorSizeFloor":"1"},"sdkToken":"' + api_token + '","settlementVersionCode":3050,"skuSource":0,"sourceType":2,"supportAllEncode":true,"supportNewParamEncode":true,"wareId":"' + skuid + '","wareNum":1}'
    sign = getSign(functionId=functionId, body=body_data, client='android', clientVersion=clientVersion,
                   uuid=deviceId)
    result = sign.split('&')
    url = 'https://api.m.jd.com/client.action'
    headers = {
        'user-agent': 'sprite/1.0.0;jdmall;android;version/13.2.9',
        'x-rp-client': 'android_4.0.0',
        'X-referer-package': 'com.jingdong.app.mall',
        'charset': 'UTF-8',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-httpdns-route': '111.202.127.106',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'accept-encoding': 'br,gzip,deflate',
        'x-pp-aew': '68',
        'cache-control': 'no-cache',
        'j-e-c': jec,
        "Cookie": cookies
    }
    params = {
        'functionId': functionId,
        'clientVersion': clientVersion,
        'build': '100533',
        'client': 'android',
        'partner': 'jingdong',
        'sdkVersion': '25',
        'lang': 'zh_CN',
        'harmonyOs': '0',
        'networkType': 'UNKNOWN',
        'uemps': '0-2-0',
        'ext': '{"prstate":"0","pvcStu":"1","cfgExt":"{\"privacyOffline\":\"0\"}"}',
        'eid': eid,
        'x-api-eid-token': api_token,
        'xAPINqe': '1',
        'xAPIDJPTransmittedData': '{"tnSDKVersion":"1.16.0"}',
        'xAPIClientLanguage': 'zh_CN',
        'xAPINeoType': '-1',
        'ef': '1',
        'ep': ep,
        'st': result[0].split('=')[1],
        'sign': result[1].split('=')[1],
        'sv': '111'
    }
    data = {
        'xAPIScval3': 0,
        'body': body_data,
        'xAPIScval2': skuid
    }
    query_string = urlencode(params)
    full_url = urljoin('/client.action', '?' + query_string)
    jdgs = jdGsService().getJdgs(
        eid=params['eid'],
        url=full_url, body=body_data)
    headers['jdgs'] = jdgs
    resp = sess.post(url=url, headers=headers, params=params, data=data, verify=False, impersonate="chrome99_android")
    print(resp.text)
    return json.loads(resp.text)


def hostTest():
    url = 'https://share.proxy.qg.net/get?key=L0RENZ68&num=1&area=320100,320200,320300,320400,320500,320600,320700,320800,320900,321000,321100,321200,321300&isp=0&format=json&distinct=true'
    headers = {
        'user-agent': 'sprite/1.0.0;jdmall;android;version/13.2.9',
        'x-rp-client': 'android_4.0.0',
        'X-referer-package': 'com.jingdong.app.mall',
        'charset': 'UTF-8',
        'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-httpdns-route': '111.202.127.106',
        'x-referer-page': 'com.jingdong.app.mall.MainFrameActivity',
        'accept-encoding': 'br,gzip,deflate',
        'x-pp-aew': '68',
        'cache-control': 'no-cache'
    }
    resp = sess.get(url=url, headers=headers)
    proxy = resp.json()
    proxy_ip = random.choice(proxy['data'])
    print(proxy)
    username = 'd2222698982'
    password = 'kniqh7uw'
    sess.proxies = {
        "https": "http://{0}/".format(proxy_ip['server'])
    }
    print(sess.proxies)
    get_current_ip_address()


def get_current_ip_address():
    # https://httpbin.org/ip
    t1 = int(round(time.time() * 1000))
    response = sess.post("https://quic-api.m.jd.com")
    t2 = int(round(time.time() * 1000))
    print(t2-t1)


if __name__ == "__main__":
    '''
    cipher加解密
    '''
    enc_body = 'oyTrZQHyZXDzIWGsEsSnCtuyDNO1EJG1CMSiSwPmcQnvG2PyZIS6CMmsYxVzaW5vc3DTZMS6SsSiSwDrcxHMdW5ubQVWZXTzaW9kStesCJUmCtKsBMTtYXT0UwVndWVz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H5cQUsEsSnSx0='
    print(body_dec(data=cartRemove))
    hostTest()
    # body = 'ALN-AL80'
    # enc_result = body_enc(data=body)
    # print(enc_result)
    # get_uts()
    # get_address()
    # appPoint()
    # cart()
    # batchDelete()
    # cartAdd()
    # currentOrder()
    # body = '%E8%AE%B0%E5%BF%86%E6%B7%B1%E5%9F%8Bde%E9%82%A3%E7%89%87%E5%BF%83%E6%B5%B7'
    # print(body_enc(data=body))
    # uuid = sign_uuid()
    # print(uuid)
    # eid = get_eid(android_id=uuid)
    # print(eid)
    # info = get_JMA(wifi_mac='', uuid=uuid, eid=eid, wskey='AAJn_gynAEAN08OdDEeoWgbz-Ujpdrguy2Mokeo4nPMDH-rFlVRpGHeWwmdWS2X2WAIsAQfGY6-AzeP8uQv8_3c2-DQpNZzT')
    # print(info)
